package cn.qdhlm.access.preview;

import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.DatabaseBuilder;
import com.healthmarketscience.jackcess.Table;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class WriteAccess {
    public static void main(String[] args) {
        Database database = openDB();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                List<Map<String, Object>> recordList = new ArrayList<>();
                Map<String, Object> recordMap;
                for (int i = 0; i < 10; i++) {
                    recordMap = new HashMap<>();
                    recordMap.put("age", i);
                    recordMap.put("user_name", "zhangsan_" + i);
                    recordMap.put("address", "tianan_" + i);
                    recordMap.put("status", 0);
                    recordMap.put("createTime", "2021-01-07");
                    recordList.add(recordMap);
                }

                write(database, "t_sys_user", recordList);
            }
        }, 0, 1000);
    }

    private static Database openDB() {
        Database database = null;
        try {
            database = DatabaseBuilder.open(new File("D:\\workspace\\access\\test.mdb"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return database;
    }

    private static void write(Database database, String tableName, List<Map<String, Object>> recordList) {
        Table table = null;
        try {
            table = database.getTable(tableName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (null != table) {
            try {
                table.addRowsFromMaps(recordList);

                System.out.println("recordList.size:" + recordList.size());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
